<template>
  <div class="settings-container">
    <div class="settings-content">
      <!-- 安全设置 -->
      <a-card class="general-card" :bordered="false">
        <template #title>
          <div class="card-title">
            <icon-safe class="icon" />
            <span>安全设置</span>
          </div>
        </template>
        <a-space direction="vertical" :size="20" fill>
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">
                <icon-lock class="item-icon" />
                登录密码
              </div>
              <div class="setting-item-desc">
                建议您定期更改密码，设置更强密码
              </div>
            </div>
            <div class="setting-item-right">
              <a-button
                type="outline"
                status="success"
                @click="showPasswordModal = true"
              >
                修改密码
              </a-button>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">
                <icon-mobile class="item-icon" />
                手机绑定
              </div>
              <div class="setting-item-desc">已绑定：{{ userInfo.phone }}</div>
            </div>
            <div class="setting-item-right">
              <a-button
                type="outline"
                status="success"
                @click="showPhoneModal = true"
              >
                修改手机号
              </a-button>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">
                <icon-email class="item-icon" />
                邮箱绑定
              </div>
              <div class="setting-item-desc">已绑定：{{ userInfo.email }}</div>
            </div>
            <div class="setting-item-right">
              <a-button
                type="outline"
                status="success"
                @click="showEmailModal = true"
              >
                修改邮箱
              </a-button>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">
                <icon-safe class="item-icon" />
                两步验证
              </div>
              <div class="setting-item-desc">
                开启后登录需要进行二次验证，提高账号安全性
              </div>
            </div>
            <div class="setting-item-right">
              <a-switch v-model="securitySettings.twoFactor" @change="updateSecuritySettings" />
            </div>
          </div>
        </a-space>
      </a-card>

      <!-- 通知设置 -->
      <a-card class="general-card" :bordered="false">
        <template #title>
          <div class="card-title">
            <icon-notification class="icon" />
            <span>通知设置</span>
          </div>
        </template>
        <a-space direction="vertical" :size="20" fill>
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">系统消息</div>
              <div class="setting-item-desc">接收系统更新、维护等通知</div>
            </div>
            <div class="setting-item-right notification-right">
              <a-space>
                <a-checkbox v-model="notificationSettings.systemEmail" @change="updateNotificationSettings"
                  >邮件</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.systemSms" @change="updateNotificationSettings"
                  >短信</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.systemPush" @change="updateNotificationSettings"
                  >站内信</a-checkbox
                >
              </a-space>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">订单通知</div>
              <div class="setting-item-desc">接收新订单、退款等业务通知</div>
            </div>
            <div class="setting-item-right notification-right">
              <a-space>
                <a-checkbox v-model="notificationSettings.orderEmail" @change="updateNotificationSettings"
                  >邮件</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.orderSms" @change="updateNotificationSettings"
                  >短信</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.orderPush" @change="updateNotificationSettings"
                  >站内信</a-checkbox
                >
              </a-space>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">安全通知</div>
              <div class="setting-item-desc">接收账号登录、修改等安全通知</div>
            </div>
            <div class="setting-item-right notification-right">
              <a-space>
                <a-checkbox v-model="notificationSettings.securityEmail" @change="updateNotificationSettings"
                  >邮件</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.securitySms" @change="updateNotificationSettings"
                  >短信</a-checkbox
                >
                <a-checkbox v-model="notificationSettings.securityPush" @change="updateNotificationSettings"
                  >站内信</a-checkbox
                >
              </a-space>
            </div>
          </div>
        </a-space>
      </a-card>

      <!-- 偏好设置 -->
      <a-card class="general-card" :bordered="false">
        <template #title>
          <div class="card-title">
            <icon-settings class="icon" />
            <span>偏好设置</span>
          </div>
        </template>
        <a-space direction="vertical" :size="20" fill>
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">界面主题</div>
              <div class="setting-item-desc">设置系统的显示主题</div>
            </div>
            <div class="setting-item-right">
              <a-radio-group 
                v-model="preferenceSettings.theme" 
                type="button"
                @change="updatePreferenceSettings"
              >
                <a-radio value="light">浅色</a-radio>
                <a-radio value="dark">深色</a-radio>
                <a-radio value="auto">跟随系统</a-radio>
              </a-radio-group>
            </div>
          </div>
          <a-divider style="margin: 0" />
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">语言</div>
              <div class="setting-item-desc">设置系统显示语言</div>
            </div>
            <div class="setting-item-right">
              <a-select
                v-model="preferenceSettings.language"
                style="width: 120px"
                @change="updatePreferenceSettings"
              >
                <a-option value="zh-CN">简体中文</a-option>
                <a-option value="en-US">English</a-option>
              </a-select>
            </div>
          </div>
          <div class="setting-item">
            <div class="setting-item-left">
              <div class="setting-item-title">导出设置</div>
              <div class="setting-item-desc">导出当前所有设置</div>
            </div>
            <div class="setting-item-right">
              <a-button type="outline" status="success" @click="exportSettings">
                导出设置
              </a-button>
            </div>
          </div>
        </a-space>
      </a-card>
    </div>

    <!-- 修改密码弹窗 -->
    <a-modal
      v-model:visible="showPasswordModal"
      title="修改密码"
      @ok="handlePasswordChange"
      @cancel="resetPasswordForm"
    >
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item
          field="oldPassword"
          label="当前密码"
          validate-trigger="blur"
        >
          <a-input-password
            v-model="passwordForm.oldPassword"
            placeholder="请输入当前密码"
          />
        </a-form-item>
        <a-form-item field="newPassword" label="新密码" validate-trigger="blur">
          <a-input-password
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>
        <a-form-item
          field="confirmPassword"
          label="确认新密码"
          validate-trigger="blur"
        >
          <a-input-password
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改手机号弹窗 -->
    <a-modal
      v-model:visible="showPhoneModal"
      title="修改手机号"
      @ok="handlePhoneChange"
      @cancel="resetPhoneForm"
    >
      <a-form :model="phoneForm" layout="vertical">
        <a-form-item field="newPhone" label="新手机号" validate-trigger="blur">
          <a-input v-model="phoneForm.newPhone" placeholder="请输入新手机号" />
        </a-form-item>
        <a-form-item field="verificationCode" label="验证码">
          <a-space>
            <a-input
              v-model="phoneForm.verificationCode"
              placeholder="请输入验证码"
            />
            <a-button
              type="primary"
              :disabled="phoneForm.countdown > 0"
              @click="sendPhoneCode"
            >
              {{
                phoneForm.countdown > 0
                  ? `${phoneForm.countdown}s后重新发送`
                  : "发送验证码"
              }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改邮箱弹窗 -->
    <a-modal
      v-model:visible="showEmailModal"
      title="修改邮箱"
      @ok="handleEmailChange"
      @cancel="resetEmailForm"
    >
      <a-form :model="emailForm" layout="vertical">
        <a-form-item field="newEmail" label="新邮箱" validate-trigger="blur">
          <a-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
        </a-form-item>
        <a-form-item field="verificationCode" label="验证码">
          <a-space>
            <a-input
              v-model="emailForm.verificationCode"
              placeholder="请输入验证码"
            />
            <a-button
              type="primary"
              :disabled="emailForm.countdown > 0"
              @click="sendEmailCode"
            >
              {{
                emailForm.countdown > 0
                  ? `${emailForm.countdown}s后重新发送`
                  : "发送验证码"
              }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { Message } from "@arco-design/web-vue";
import { useUserStore } from "@/stores/user";
import service from "@/api/axios";
import * as XLSX from 'xlsx';
import {
  IconSafe,
  IconLock,
  IconMobile,
  IconEmail,
  IconNotification,
  IconSettings,
} from "@arco-design/web-vue/es/icon";

const userStore = useUserStore();

// 用户基本信息（默认测试数据）
const userInfo = ref({
  phone: "138****8000",
  email: "a***@example.com",
  avatar: "",
});

// 安全设置（默认测试数据）
const securitySettings = reactive({
  twoFactor: false,
});

// 通知设置（默认测试数据）
const notificationSettings = reactive({
  systemEmail: true,
  systemSms: true,
  systemPush: true,
  orderEmail: true,
  orderSms: true,
  orderPush: true,
  securityEmail: true,
  securitySms: true,
  securityPush: true,
});

// 偏好设置（默认测试数据）
const preferenceSettings = reactive({
  theme: "light",
  language: "zh-CN",
});

// 修改密码相关
const showPasswordModal = ref(false);
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 修改手机号相关
const showPhoneModal = ref(false);
const phoneForm = reactive({
  newPhone: "",
  verificationCode: "",
  countdown: 0,
});

// 修改邮箱相关
const showEmailModal = ref(false);
const emailForm = reactive({
  newEmail: "",
  verificationCode: "",
  countdown: 0,
});

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 获取安全设置
const fetchSecuritySettings = async () => {
  try {
    const response = await service.get("/admin/security-settings");
    securitySettings.twoFactor = response.data.twoFactor;
    userInfo.value.phone = response.data.phone;
    userInfo.value.email = response.data.email;
  } catch (error) {
    console.error("获取安全设置失败:", error);
    // 使用默认测试数据
  }
};

// 获取通知设置
const fetchNotificationSettings = async () => {
  try {
    const response = await service.get("/admin/notification-settings");
    Object.assign(notificationSettings, response.data);
  } catch (error) {
    console.error("获取通知设置失败:", error);
    // 使用默认测试数据
  }
};

// 获取偏好设置
const fetchPreferenceSettings = async () => {
  try {
    const response = await service.get("/admin/preference-settings");
    preferenceSettings.theme = response.data.theme;
    preferenceSettings.language = response.data.language;
    
    // 应用主题设置
    handleThemeChange(preferenceSettings.theme);
    
    // 应用语言设置
    handleLanguageChange(preferenceSettings.language);
  } catch (error) {
    console.error("获取偏好设置失败:", error);
    // 使用默认测试数据
  }
};

// 更新安全设置
const updateSecuritySettings = async () => {
  try {
    await service.put("/admin/security-settings", {
      twoFactor: securitySettings.twoFactor
    });
    Message.success("安全设置已更新");
  } catch (error) {
    console.error("更新安全设置失败:", error);
    Message.error("设置更新失败");
    // 回滚设置
    await fetchSecuritySettings();
  }
};

// 更新通知设置
const updateNotificationSettings = async () => {
  try {
    await service.put("/admin/notification-settings", notificationSettings);
    Message.success("通知设置已更新");
  } catch (error) {
    console.error("更新通知设置失败:", error);
    Message.error("设置更新失败");
    // 回滚设置
    await fetchNotificationSettings();
  }
};

// 更新偏好设置
const updatePreferenceSettings = async () => {
  try {
    await service.put("/admin/preference-settings", {
      theme: preferenceSettings.theme,
      language: preferenceSettings.language
    });
    
    // 应用主题设置
    handleThemeChange(preferenceSettings.theme);
    
    // 应用语言设置
    handleLanguageChange(preferenceSettings.language);
    
    Message.success("偏好设置已更新");
  } catch (error) {
    console.error("更新偏好设置失败:", error);
    Message.error("设置更新失败");
    // 回滚设置
    await fetchPreferenceSettings();
  }
};

// 修改密码
const handlePasswordChange = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    Message.error("两次输入的密码不一致");
    return;
  }
  
  try {
    const response = await service.post("/admin/change-password", {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    });
    
    Message.success("密码修改成功");
    showPasswordModal.value = false;
    resetPasswordForm();
  } catch (error) {
    console.error("密码修改失败:", error);
    Message.error(error.response?.data?.message || "密码修改失败");
  }
};

// 修改手机号
const handlePhoneChange = async () => {
  try {
    const response = await service.post("/admin/change-phone", {
      newPhone: phoneForm.newPhone,
      verificationCode: phoneForm.verificationCode
    });
    
    Message.success("手机号修改成功");
    showPhoneModal.value = false;
    resetPhoneForm();
    
    // 重新获取安全设置以更新界面
    await fetchSecuritySettings();
  } catch (error) {
    console.error("手机号修改失败:", error);
    Message.error(error.response?.data?.message || "手机号修改失败");
  }
};

// 修改邮箱
const handleEmailChange = async () => {
  try {
    const response = await service.post("/admin/change-email", {
      newEmail: emailForm.newEmail,
      verificationCode: emailForm.verificationCode
    });
    
    Message.success("邮箱修改成功");
    showEmailModal.value = false;
    resetEmailForm();
    
    // 重新获取安全设置以更新界面
    await fetchSecuritySettings();
  } catch (error) {
    console.error("邮箱修改失败:", error);
    Message.error(error.response?.data?.message || "邮箱修改失败");
  }
};

// 发送手机验证码
const sendPhoneCode = async () => {
  try {
    await service.post("/admin/send-phone-code", {
      phone: phoneForm.newPhone
    });
    
    phoneForm.countdown = 60;
    const timer = setInterval(() => {
      if (phoneForm.countdown > 0) {
        phoneForm.countdown--;
      } else {
        clearInterval(timer);
      }
    }, 1000);
    
    Message.success("验证码已发送");
  } catch (error) {
    console.error("验证码发送失败:", error);
    Message.error(error.response?.data?.message || "验证码发送失败");
  }
};

// 发送邮箱验证码
const sendEmailCode = async () => {
  try {
    await service.post("/admin/send-email-code", {
      email: emailForm.newEmail
    });
    
    emailForm.countdown = 60;
    const timer = setInterval(() => {
      if (emailForm.countdown > 0) {
        emailForm.countdown--;
      } else {
        clearInterval(timer);
      }
    }, 1000);
    
    Message.success("验证码已发送");
  } catch (error) {
    console.error("验证码发送失败:", error);
    Message.error(error.response?.data?.message || "验证码发送失败");
  }
};

// 导出设置为Excel
const exportSettings = () => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  
  // 安全设置数据
  const securityData = [
    ["安全设置", "值"],
    ["两步验证", securitySettings.twoFactor ? "已开启" : "已关闭"],
    ["邮箱绑定", userInfo.value.email],
    ["手机绑定", userInfo.value.phone],
  ];
  
  // 通知设置数据
  const notificationData = [
    ["通知类型", "邮件", "短信", "站内信"],
    ["系统消息", notificationSettings.systemEmail ? "是" : "否", 
             notificationSettings.systemSms ? "是" : "否", 
             notificationSettings.systemPush ? "是" : "否"],
    ["订单通知", notificationSettings.orderEmail ? "是" : "否", 
             notificationSettings.orderSms ? "是" : "否", 
             notificationSettings.orderPush ? "是" : "否"],
    ["安全通知", notificationSettings.securityEmail ? "是" : "否", 
             notificationSettings.securitySms ? "是" : "否", 
             notificationSettings.securityPush ? "是" : "否"],
  ];
  
  // 偏好设置数据
  const preferenceData = [
    ["偏好设置", "值"],
    ["主题", preferenceSettings.theme === "light" ? "浅色" : 
           preferenceSettings.theme === "dark" ? "深色" : "跟随系统"],
    ["语言", preferenceSettings.language === "zh-CN" ? "简体中文" : "English"],
  ];
  
  // 创建工作表
  const securitySheet = XLSX.utils.aoa_to_sheet(securityData);
  const notificationSheet = XLSX.utils.aoa_to_sheet(notificationData);
  const preferenceSheet = XLSX.utils.aoa_to_sheet(preferenceData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, securitySheet, "安全设置");
  XLSX.utils.book_append_sheet(workbook, notificationSheet, "通知设置");
  XLSX.utils.book_append_sheet(workbook, preferenceSheet, "偏好设置");
  
  // 导出Excel
  XLSX.writeFile(workbook, `管理员设置_${new Date().toISOString().split('T')[0]}.xlsx`);
};

// 重置表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = "";
  passwordForm.newPassword = "";
  passwordForm.confirmPassword = "";
};

const resetPhoneForm = () => {
  phoneForm.newPhone = "";
  phoneForm.verificationCode = "";
};

const resetEmailForm = () => {
  emailForm.newEmail = "";
  emailForm.verificationCode = "";
};

// 监听主题变化
const handleThemeChange = (theme) => {
  document.body.setAttribute("arco-theme", theme);
};

// 监听语言变化
const handleLanguageChange = (language) => {
  // 这里添加切换语言的逻辑
  console.log("语言已切换到:", language);
};

// 页面加载时获取数据
onMounted(async () => {
  // 分散API调用时间，避免一次性触发过多的DOM更新
  setTimeout(async () => {
    await fetchSecuritySettings();
    setTimeout(async () => {
      await fetchNotificationSettings();
      setTimeout(async () => {
        await fetchPreferenceSettings();
      }, 100);
    }, 100);
  }, 100);

  // 添加ResizeObserver错误处理
  const originalError = console.error;
  console.error = (...args) => {
    if (args[0]?.includes?.('ResizeObserver') || 
        args[0]?.message?.includes?.('ResizeObserver') ||
        args[0]?.toString?.()?.includes?.('ResizeObserver')) {
      // 忽略ResizeObserver错误
      return;
    }
    originalError.apply(console, args);
  };
});

// 组件卸载前的清理工作
onBeforeUnmount(() => {
  // 确保重置任何可能的监听
  if (window.__resizeObserver) {
    window.__resizeObserver.disconnect();
  }
});
</script>

<style lang="less" scoped>
.settings-container {
  padding: 32px;
  background-color: var(--color-fill-2);
  min-height: calc(100vh - 60px); // 减去顶部导航栏高度

  .settings-content {
    max-width: 1200px;
    margin: 0 auto;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 24px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }

    .general-card {
      height: fit-content;
      border-radius: 12px;
      background-color: var(--color-bg-2);
      transition: all 0.3s ease;
      border: 1px solid var(--color-border);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
      }

      :deep(.arco-card-header) {
        border-bottom: 1px solid var(--color-border);
        padding: 20px 24px;
        background-color: var(--color-fill-1);
        border-radius: 12px 12px 0 0;

        .card-title {
          display: flex;
          align-items: center;
          font-size: 16px;
          font-weight: 600;
          color: var(--color-text-1);

          .icon {
            margin-right: 12px;
            font-size: 20px;
            color: rgb(var(--primary-6));
          }
        }
      }

      :deep(.arco-card-body) {
        padding: 0;
      }
    }

    .setting-item {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      padding: 20px 24px;
      transition: background-color 0.2s ease;
      min-height: 20px; // 给元素一个最小高度
      will-change: transform; // 提示浏览器这个元素会变化
      transform: translateZ(0); // 触发GPU加速

      &:not(:last-child) {
        border-bottom: 1px solid var(--color-border);
      }

      &:hover {
        background-color: var(--color-fill-1);
      }

      .setting-item-left {
        flex: 1;
        margin-right: 24px;

        .setting-item-title {
          display: flex;
          align-items: center;
          font-size: 15px;
          font-weight: 500;
          color: var(--color-text-1);
          margin-bottom: 8px;

          .item-icon {
            margin-right: 8px;
            font-size: 18px;
            color: rgb(var(--primary-6));
          }
        }

        .setting-item-desc {
          font-size: 13px;
          color: var(--color-text-3);
          line-height: 1.5;
        }
      }

      .setting-item-right {
        min-width: 200px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .arco-btn {
          padding: 0 20px;
          height: 32px;
          font-size: 14px;
          border-radius: 6px;

          &:hover {
            transform: translateY(-1px);
          }
        }

        &.notification-right {
          min-width: auto;

          .arco-checkbox {
            margin-right: 24px;

            &:last-child {
              margin-right: 0;
            }

            :deep(.arco-checkbox-label) {
              color: var(--color-text-2);
            }
          }
        }

        .arco-radio-group {
          .arco-radio-button {
            height: 32px;
            line-height: 30px;
            padding: 0 16px;
          }
        }

        .arco-select {
          .arco-select-view {
            border-radius: 6px;
          }
        }
      }
    }
  }
}

// 弹窗样式优化
:deep(.arco-modal) {
  .arco-modal-header {
    border-bottom: 1px solid var(--color-border);
    padding: 20px 24px;

    .arco-modal-title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .arco-modal-body {
    padding: 24px;
  }

  .arco-modal-footer {
    border-top: 1px solid var(--color-border);
    padding: 16px 24px;
  }

  .arco-form-item-label {
    font-weight: 500;
  }

  .arco-input-wrapper,
  .arco-input-password {
    border-radius: 6px;
  }

  // 避免弹窗尺寸频繁变化
  will-change: transform;
  transform: translateZ(0);
}

// 开关样式优化
:deep(.arco-switch) {
  &.arco-switch-checked {
    background-color: rgb(var(--success-6));
  }
}
</style>
